﻿@model InvoiceListModel

@using Telerik.Web.Mvc.UI
@using Nop.Core.Domain.Orders

@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    var hideProfitReport = false;

    //page title
    ViewBag.Title = T("Admin.Invoice").Text;
}

@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Invoice")
        </div>
        <div class="options">
            <a href="@Url.Action("OrderList", new { orderKindId = (int)OrderKind.Express})" class="t-button">@T("Admin.Invoice.CreateExpressInvoice")</a>
            <a href="@Url.Action("OrderList", new { orderKindId = (int)OrderKind.Commerce})" class="t-button">@T("Admin.Invoice.CreateCommerceInvoice")</a>
            <a href="@Url.Action("BulkCreate")" class="t-button">@T("Admin.Invoice.BulkCreateInvoice")</a>
            <input type="button" id="pdf-invoices" class="t-button" value="@T("Admin.Invoice.PdfInvoices")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.Email):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.Email)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.BillingEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.BillingEmail)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderKindId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.OrderKindId, Model.AvailableOrderKinds)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DistrictId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DistrictId, Model.AvailableDistricts)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.InvoiceStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("InvoiceStatusId", Model.AvailableStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.InvoiceGuid):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.InvoiceGuid)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StoreId):
            </td>
            <td class="adminData">
                @(Html.Telerik().ComboBoxFor(model => model.StoreId)
                        .AutoFill(true)
                        .Filterable()
                        .DataBinding(binding => binding.Ajax().Select("StoreList", "Store", new { storeId = Model.StoreId, customerId = 0 })))
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToNumber)
                <input type="submit" name="go-to-invoice-by-number" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                @(Html.Telerik().Grid<InvoiceModel>()
                        .Name("invoices-grid")
                        .ClientEvents(events => events
                            .OnDataBinding("onDataBinding")
                            .OnDataBound("onDataBound")
                            .OnComplete("onComplete"))
                        .Columns(columns =>
                        {
                            columns.Bound(x => x.Id)
                                .Filterable(false)
                                .Template(x => string.Format("<input type='checkbox' name='checkedRecords' value='{0}' class='checkboxGroups'/>", x.Id))
                                .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                                .Title("<input id='mastercheckbox' type='checkbox'/>")
                                .Width(50)
                                .HtmlAttributes(new { style = "text-align:center" })
                                .HeaderHtmlAttributes(new { style = "text-align:center" });
                            columns.Bound(x => x.Id)
                                .Centered();
                            columns.Bound(x => x.InvoiceNumber);
                            columns.Bound(x => x.District);
                            columns.Bound(x => x.CustomerEmail)
                                .Template(x => Html.ActionLink(x.CustomerEmail, "Edit", "Customer", new { id = x.CustomerId }, new { }))
                                .ClientTemplate("<a href=\"" + @Url.Content("~/Admin/Customer/Edit/") + "<#= CustomerId #>\"><#= CustomerEmail #></a>")
                                .Width(150);
                            columns.Bound(x => x.Name);
                            columns.Bound(x => x.BillingEmail);
                            columns.Bound(x => x.CustomerId);
                            columns.Bound(x => x.InvoiceStatus);
                            columns.Bound(x => x.Total)
                                 .FooterTemplate(
                                 string.Format("<div><strong>{0}:</strong></div>" +
                                 "<div>{1}: <span id=\"aggregator-tax-block\"></span></div>" +
                                 "<div>{2}: <span id=\"aggregator-total-block\"></span></div>",
                                 @T("Admin.Orders.Report.Summary").Text,
                                 @T("Admin.Orders.Report.Tax").Text,
                                 @T("Admin.Orders.Report.Total").Text));
                            columns.Bound(x => x.CreatedOn).ClientTemplate("<#= CreatedOnStr #>");
                            columns.Bound(x => x.Id)
                                .Template(x => Html.ActionLink(T("Admin.Common.Edit").Text, "Edit", new { id = x.Id }))
                                .ClientTemplate("<a href=\"Edit/<#= Id #>\">" + T("Admin.Common.Edit").Text + "</a>")
                                .Width(50)
                                .Centered()
                                .HeaderTemplate(T("Admin.Common.Edit").Text)
                                .Filterable(false);
                        })
                        .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                        .DataBinding(dataBinding => dataBinding.Ajax().Select("_InvoiceList", "Invoice", Model))
                        .EnableCustomBinding(true))
            </td>
        </tr>
    </table>

    <script type="text/javascript">

    var selectedIds = [];
    var reportAggregates = "";

    $(document).ready(function () {

        //search button
        $('#btnSearch').click(function () {
            //search
            var grid = $('#invoices-grid').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            //clear selected checkboxes
            $('.checkboxGroups').attr('checked', false).change();
            selectedIds = [];
            return false;
        });

        $('#mastercheckbox').click(function () {
            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
        });

        //wire up checkboxes.
        $('#invoices-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
            var $check = $(this);
            if ($check.is(":checked") == true) {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked == -1) {
                    //add id to selectedIds.
                    selectedIds.push($check.val());
                }
            }
            else {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked > -1) {
                    //remove id from selectedIds.
                    selectedIds = $.grep(selectedIds, function (item, index) {
                        return item != $check.val();
                    });
                }
            }
            updateMasterCheckbox();
        });

        //"Pdf Invoices" button
        $('#pdf-invoices').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("PdfInvoices", "Invoice"))?selectedIds=' + selectedIds.join(","));
            return false;
        });
    });

    function onComplete(e) {
        var result = e.response;
        if (result) {
            reportAggregates = e.response["aggregates"];
        }
    }

    function reportLoaded(e) {
        if (reportAggregates != "") {
            updateAggregates(reportAggregates);
        }
    }

    function updateAggregates(aggs) {
        for (var key in aggs) {
            $('#aggregator-tax-block').text(aggs['aggregatortax']);
            $('#aggregator-total-block').text(aggs['aggregatortotal']);
        }
    }

    function onDataBinding(e) {
        var searchModel = {
            StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
            EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
            Email: $('#@Html.FieldIdFor(model => model.Email)').val(),
            BillingEmail: $('#@Html.FieldIdFor(model => model.BillingEmail)').val(),
            InvoiceGuid: $('#@Html.FieldIdFor(model => model.InvoiceGuid)').val(),
            Name: $('#@Html.FieldIdFor(model => model.Name)').val(),
            InvoiceStatusId: $('#@Html.FieldIdFor(model => model.InvoiceStatusId)').val(),
            OrderKindId: $('#@Html.FieldIdFor(model => model.OrderKindId)').val(),
            DistrictId: $('#@Html.FieldIdFor(model => model.DistrictId)').val(),
            StoreId: $('#@Html.FieldIdFor(model => model.StoreId)').val()
        };
        e.data = searchModel;
    }

    function onDataBound(e) {
        $('#invoices-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
            var currentId = $(this).val();
            var checked = jQuery.inArray(currentId, selectedIds);
            //set checked based on if current checkbox's value is in selectedIds.
            $(this).attr('checked', checked > -1);
        });

        updateMasterCheckbox();

        reportLoaded(e);
    }

    function updateMasterCheckbox() {
        var numChkBoxes = $('#invoices-grid input[type=checkbox][id!=mastercheckbox]').length;
        var numChkBoxesChecked = $('#invoices-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }
</script>

}